/**
 * 
 */
package com.munoor.dalai.server.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.munoor.dalai.server.model.EMFService;
import com.munoor.dalai.server.model.User;
import com.munoor.dalai.server.utils.Hash;

/**
 * @author Ilamah, Osho 31 March 2011
 */
public final class AuthenticationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session;
		String requestURI = request.getRequestURI();
		if (requestURI.indexOf("logout") > -1) {
			// logout request
			session = request.getSession(false);
			if (session != null) {
				session.invalidate();
			}
			response.setStatus(HttpServletResponse.SC_OK);
		} else if (requestURI.indexOf("login") > -1){
			// login request
			BufferedReader reader = request.getReader();
			ObjectMapper mapper = new ObjectMapper();
			User clientUser = null;
			try {
				clientUser = mapper.readValue(reader, User.class);
		    } catch (Exception e1) { // in case malformed JSON posted and can
										// not be unmasshalled by Jackson
				//response.setHeader("WWW-Authenticate", "Basic realm=\"Authentication Manager\"");
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
				return;
			} finally {
				reader.close();
			}

			EntityManager em = EMFService.get().createEntityManager();
			User registeredUser = null;
			try {
				registeredUser = (User) em.createNamedQuery("Users.findByUsername").setParameter("username", clientUser.getUsername()).getSingleResult();
			} catch (Exception e) {
				// e.printStackTrace();
			} finally {
				em.close();
			}
			if (registeredUser != null) {
				if(registeredUser.getUserType() > 3){
					//not activated
					/* TODO Block logon with inactive account by decomment both below  */
					//response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Account inactive");
					//return;
				}
				if ((Hash.getMD5Hash(clientUser.getPassword(), registeredUser.getWelcome())).equals(registeredUser.getPassword())) {
					registeredUser.setPassword("");
					registeredUser.setWelcome(0);
					session = request.getSession();
					session.setAttribute("userid", registeredUser);
					response.setContentType("application/json");
					response.setStatus(HttpServletResponse.SC_OK);
					PrintWriter out = response.getWriter();
					out.println("{\"userId\":" + registeredUser.getUserId() + ", \"userType\":" + registeredUser.getUserType() + ", \"email\":\"" + registeredUser.getEmail() + 
							 "\", \"lastScan\":" + registeredUser.getLastScan() +"}"	);  
					out.close();
					return;
				}
			}
			//response.setHeader("WWW-Authenticate", "Basic realm=\"Authentication Manager\"");
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		}else{
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURI = request.getRequestURI();
		String code = request.getParameter("code");
		System.out.println(code);
		if ((requestURI.indexOf("verify") > -1) && (code != null)) {
			EntityManager em = EMFService.get().createEntityManager();
			User registeredUser = null;
			try {
				registeredUser = (User) em.createNamedQuery("Users.findByVerifyCode").setParameter("vCode", code).getSingleResult();
				if (registeredUser.getUserType() > 3){
					registeredUser.setUserType((short) 2);
					// if currently active session, update user level
					HttpSession session = request.getSession(false);
					if (session != null) {
						User user = (User) (session.getAttribute("userid"));
						if (user != null) {
							user.setUserType(registeredUser.getUserType());
							session.setAttribute("userid", user);
						}
					}					
				}
			} catch (Exception e) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST); // user not found
			} finally {
				em.close();
			}
		} else {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}

	}

}
